package com.legrand.www.module.common.controller;

import com.legrand.www.module.core.entity.User;
import com.legrand.www.module.security.util.UserUtil;
import com.legrand.www.module.core.response.BaseResponse;
import com.legrand.www.module.core.util.JwtToken;
import com.legrand.www.module.core.util.TokenUtil;
import com.legrand.www.module.common.util.PhoneAndIDcardCheckUtil;
import com.legrand.www.module.exception.exception.ExceptionBase;
import com.legrand.www.module.common.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;


/**
 * @author xiah
 * @date 2018/4/26 16:24
 */
@Controller
@RequestMapping("/api/auth")
public class TokenController {

       @Autowired
       private UserService userService;

       @RequestMapping(value = "/sec/test")
       @ResponseBody
       public BaseResponse test() {
              String name = UserUtil.getUserName();
              return new BaseResponse(name);

       }

       /**
        * @author xiah
        * description: 用户通过手机号和验证码获得token，refresh_token等信息
        * date: 2018/4/26
        */
       @RequestMapping(value = "/sec/getTokeByMobile", method = RequestMethod.POST)
       @ResponseBody
       public BaseResponse getTokeByMobile(@RequestParam String mobilePhone, @RequestParam String code) {
              if ( !PhoneAndIDcardCheckUtil.isTelephone(mobilePhone) ) {
                     throw new ExceptionBase(122, "phoneNumber is wrong");
              }
              /*登陆成功将用户信息保存到UserUtil*/
              String name = UserUtil.getUserName();
              return new BaseResponse(name);
              //return new BaseResponse(JwtToken.creatTokenMap());
              //userService.getUser();
              //return "";
       }

       /**
        * @author xiah
        * description: 用户通过手机号和验证码获得token，refresh_token等信息
        * date: 2018/4/26
        */
       @RequestMapping(value = "/refreshToke")
       @ResponseBody
       public BaseResponse refreshToke(HttpServletRequest request, HttpServletResponse response) throws Exception {
              request.getHeader("refresh_token");
              String refresh_token = request.getHeader("refresh_token");
              Optional<User> uu = Optional.of(new User());
              if ( refresh_token == null ) {
                     throw new ExceptionBase(122, "phoneNumber is wrong");
              }
              if ( !JwtToken.checkToken(TokenUtil.interceptToken(refresh_token)) ) {
                     response.setStatus(500);
                     throw new ExceptionBase(122, "phoneNumber is wrong");
              }
              return new BaseResponse(JwtToken.createToken());
              //userService.getUser();
              //return "";

       }
}
